<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { useUser } from '~/stroes/user'

const props = defineProps<{
    // 从父组件传递过来的可选参数 type
    type?: string
}>()
// 向父组件传递任务完成事件
const emit = defineEmits(['success'])

const user = useUser()
// 是否关闭表单
const disabled = ref(false)
// 临时储存表单数据
const userFormData = ref({
    name: '',
    email: '',
    password: '',
    confirmPassword: ''
})
// 表单实例
const formRef = ref<FormInstance>()

// 表单验证
const formRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
    email: [
        // 邮箱注册时必填，登陆时不需要
        { required: props.type === 'signup', message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: ['blur', 'change'] },
        {
            validator: (_rule, _value, callback) => {
                // 有时用户输入到确认密码后，发现之前的密码有误，修改了之前的密码
                // 如果不增加这个校验逻辑，用户还需要重新操作确认密码输入框才能触发校验
                if (props.type === 'signup' && userFormData.value.confirmPassword !== '') {
                    // 触发确认密码的验证
                    formRef.value?.validateField('confirmPassword').catch((err) => {
                        if (import.meta.env.DEV) { window.console.log(err) }
                    })
                }
                callback()
            },
            trigger: ['blur', 'change']
        }
    ],
    confirmPassword: [
        // 确认密码注册时必填，登陆时不需要
        { required: props.type === 'signup', message: '请再次输入密码', trigger: 'blur' },
        { min: 6, max: 12, message: '长度在 6 到 12 个字符', trigger: ['blur', 'change'] },
        {
            validator: (_rule, value, callback) => {
                if (value === userFormData.value.password) {
                    callback()
                } else {
                    callback(new Error('两次输入密码不一致'))
                }
            },
            trigger: ['blur', 'change']
        }
    ]
})

function post (path = 'login') {
    if (!formRef.value) { return }
    // 防止重复提交
    disabled.value = true
    // 登录无须验证邮箱
    if (path === 'login') {
        userFormData.value.email = ''
    }
    // 开发环境下打印数据
    if (import.meta.env.DEV) { window.console.log(`Form ${path}`) }
    formRef.value.validate((valid) => {
        if (!valid) {
            // 校验不通过，不执行注册
            if (import.meta.env.DEV) { window.console.log(`Form ${path} validate failed`) }
            ElMessage.error('请检查输入格式是否正确')
            // 重置状态
            disabled.value = false
            return false
        }
        if (import.meta.env.DEV) { window.console.log(`Form ${path} validate success`) }
        // 校验通过，注册
        user.$patch({
            name: userFormData.value.name,
            email: userFormData.value.email
        })
        user.postUser(path, userFormData.value.password)
            .then((req) => {
                if (import.meta.env.DEV) { window.console.log(req) }
                if (req?.errMsg) {
                    ElMessage.error(req.errMsg)
                    return
                }
                // 登录成功
                if (user.isLogged) {
                    emit('success')
                }
            })
            .catch((err) => {
                if (import.meta.env.DEV) { window.console.log(err) }
                ElMessage.error(err)
            })
            .finally(() => {
                // 重置状态
                disabled.value = false
            })
    })
}

// submit按钮的点击事件
const submit = () => {
    post(props.type)
}
</script>

<template>
    <el-form
        ref="formRef"
        v-loading="disabled"
        :model="userFormData"
        :rules="formRules"
        class="form"
        hide-required-asterisk
        label-position="top"
        label-width="80px"
        scroll-to-error
        status-icon
        @keydown.enter="submit"
    >
        <el-form-item autocomplete="username" label="用户名" prop="name">
            <el-input v-model="userFormData.name" />
        </el-form-item>
        <el-form-item v-if="type === 'signup'" autocomplete="email" label="邮箱" prop="email">
            <el-input v-model="userFormData.email" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input
                v-model="userFormData.password"
                :autocomplete="type === 'signup' ? 'new-password' : 'off'"
                show-password
            />
        </el-form-item>
        <el-form-item v-if="type === 'signup'" label="确认密码" prop="confirmPassword">
            <el-input
                v-model="userFormData.confirmPassword"
                :disabled="!userFormData.password"
                autocomplete="new-password"
                show-password
            />
        </el-form-item>
        <el-form-item>
            <el-button :disabled="disabled" class="submit" type="primary" @click="submit">
                {{ type === 'signup' ? '注册' : '登录' }}
            </el-button>
        </el-form-item>
    </el-form>
</template>
<!-- 私有样式,只会影响当前组件的元素 -->
<style scoped>
.form {
    margin: 0 auto;
}

.submit {
    width: 100%;
}
</style>
